import os
import matplotlib.pyplot as plt
import pandas as pd
from participle import LoadStopWords, Cutter
import numpy as np
from wordcloud import WordCloud
from pyecharts import options as opts
from pyecharts.charts import Bar
from pyecharts.faker import Faker
from pyecharts.charts import Pie
from pyecharts.charts import Line
from pyecharts.charts import Radar
import pymysql
# 显示所有列
# pd.set_option('display.max_columns', None)
# #显示所有行
# pd.set_option('display.max_rows', None)
# #设置value的显示长度为100，默认为50
# pd.set_option('max_colwidth',100)
# 柱状图可视化
def readMysqlData():
    connect = pymysql.connect(host="localhost", user="root", passwd="111111", port=3306, db="weibo", charset="utf8")
    sql = "select * from comment"
    df = pd.read_sql_query(sql,connect)
    connect.close()
    return df
def showBar(data):
    c = (
        Bar(init_opts=opts.InitOpts(width="1500px"))
            .add_xaxis(data["username"])
            .add_yaxis("点赞数", data["like"])
            # .add_yaxis("商家B", Faker.values())
            .set_global_opts(title_opts=opts.TitleOpts(title="点赞数前十柱状图"),
                             xaxis_opts=opts.AxisOpts(
                                 axislabel_opts={"interval":"0"}
                             ))
            .set_series_opts(
            label_opts=opts.LabelOpts(is_show=True),

            markpoint_opts=opts.MarkPointOpts(
                data=[
                    opts.MarkPointItem(type_="max", name="最大值"),
                    opts.MarkPointItem(type_="min", name="最小值"),
                    opts.MarkPointItem(type_="average", name="平均值"),
                ]
            ),
        )
            .render("bar_markpoint_type.html")
    )
# 饼图可视化
def showPie(data):
    x_data = data["comment"]
    y_data = data["like"]
    data_pair = [list(z) for z in zip(x_data, y_data)]
    data_pair.sort(key=lambda x: x[1])

    (
        Pie(init_opts=opts.InitOpts(width="1600px", height="800px", bg_color="#2c343c"))
            .add(
            series_name="评论内容",
            data_pair=data_pair,
            rosetype="radius",
            radius="55%",
            center=["50%", "50%"],
            label_opts=opts.LabelOpts(is_show=False, position="center"),
        )
            .set_global_opts(
            title_opts=opts.TitleOpts(
                title="评论占比",
                pos_left="center",
                pos_top="20",
                title_textstyle_opts=opts.TextStyleOpts(color="#fff"),
            ),
            legend_opts=opts.LegendOpts(is_show=False),
        )
            .set_series_opts(
            tooltip_opts=opts.TooltipOpts(
                trigger="item", formatter="{a} <br/>{b}: {c} ({d}%)"
            ),
            label_opts=opts.LabelOpts(color="rgba(255, 255, 255, 0.3)"),
        )
            .render("customized_pie.html")
    )
# 点赞饼图
def showRadar(data):
    c = (
        Pie()
            .add(
            "",
            [list(z) for z in zip(data["username"], data["like"])],
            radius=["40%", "75%"],
        )
            .set_global_opts(
            title_opts=opts.TitleOpts(title="用户:点赞   关系饼图"),
            legend_opts=opts.LegendOpts(orient="vertical", pos_top="15%", pos_left="2%"),
        )
            .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
            .render("pie_radius.html")
    )
def showLine(data):
    c = (
        Line()
            .add_xaxis(data["username"])
            .add_yaxis("用户",data["like"], areastyle_opts=opts.AreaStyleOpts(opacity=0.5))
            # .add_yaxis("商家B", Faker.values(), areastyle_opts=opts.AreaStyleOpts(opacity=0.5))
            .set_global_opts(title_opts=opts.TitleOpts(title="前十用户点赞折线面积图"))
            .render("line_area_style.html")
    )
def loadData(fn):
    """
    加载某个电影数据
    fn：文件名
    """
    return pd.read_excel(fn)


def WordCloudImage(fn, content):
    """
    功能：生成词云图
    file_path：评论文件路径
    """
    wc = WordCloud(font_path="simhei.ttf", background_color='white', collocations=False)
    wc.generate(content)
    wc.to_file('{}.png'.format(fn))


#     获取点赞数前十的评论内容
def formatData(data):
    # for (i,j) in zip(data["点赞数"],data["评论"]):
    #     print(i)
    resData = {
        "username": [],
        "like": [],
        "comment":[]
    }
    currentIndex = 0
    for index, rows in data.iterrows():
        # rows['eee'] = rows['aaa'] + rows['bbb']

        resData["username"].append(rows["名字"])
        resData["like"].append(rows["点赞数"])
        resData["comment"].append(rows["评论内容"])
        if (currentIndex > 10):
            break
        currentIndex = currentIndex + 1
    # print(resData)
    return resData
    # print(index)
    # data.iat[i, 4] = data.iat[i, 0] + data.iat[i, 1]


if __name__ == '__main__':
    data = readMysqlData()
    # # 将缺失值删掉
    data.dropna(how="all")
    # res = data.sort_values(by='点赞数', ascending=False)
    #
    # res["评论内容"].replace('', np.nan, inplace=True)
    # res.dropna(inplace=True)
    # resData = formatData(res)
    # showBar(resData)
    # showPie(resData)
    # showRadar(resData)
    # showLine(resData)
    # # print(res)
    # # print(data.info)
    stop_words = LoadStopWords()
    comments = data['评论内容'].values.tolist()
    cut_string = Cutter(comments, stop_words)
    print(cut_string)
    WordCloudImage('评论词云图', cut_string)
